import WxValidate from '../../../assets/plugins/wx-validate/WxValidate'
var bridgeApi = require('../../../utils/bridgeApi.js')
const app = getApp();
Page({
  data: {
    structureTypeNames: [],
    structureTypes: [],
    index: 0,
    bridgeData: null
  },
  onLoad: function(option) {
    this.initValidate();
    var token = app.globalData.openId;
    if (option.bridgeData) {
      let bridgeData = JSON.parse(option.bridgeData);
      let userId = (option.userId);
      let userName = (option.userName);
      this.setData({
        bridgeData: bridgeData,
        userId: userId,
        userName: userName,
      });
    }

    let structureTypes = wx.getStorageSync("structureTypes");

    if (!structureTypes) {
      bridgeApi.getStructureTypes().then((data) => {
        this.setData({
          structureTypes: structureTypes
        });
        this.setStructTypes(data);
        wx.setStorageSync("structureTypes", data);
      });
    } else {
      this.setData({
        structureTypes: structureTypes
      });
      this.setStructTypes(structureTypes);
    }
  },
  setStructTypes: function(structureTypes) {
    var structureTypeNames = [];

    for (let item of structureTypes) {
      structureTypeNames.push(item.name);
    }
    let name = this.data.bridgeData.structureTypeName;

    for (let i = 0; i < structureTypes.length; i++) {
      if (name == structureTypes[i].name) {
        this.setData({
          index: i,
          structureTypeId: structureTypes[i].id,
          structureTypeName: name,
          structureTypeValue: structureTypes[i].code,
          structureTypeNames: structureTypeNames
        });
        break;
      };
    }
  },
  // 表单提交函数
  formSubmit: function(e) {
    const params = e.detail.value;
    // 传入表单数据，调用验证方法
    if (!this.WxValidate.checkForm(params)) {
      if (this.WxValidate.errorList && this.WxValidate.errorList.length > 0) {
        this.showModal(this.WxValidate.errorList[0]);
        return false;
      }
    };
    // 获取全部数据
    var token = app.globalData.openId;
    var that = this;
    // 提交
    wx.request({
      url: app.globalData.siteUrl + '/bridge/update',
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Token": token,
      },
      data: {
        userId: that.data.userId,
        userName: that.data.userName,
        id: that.data.bridgeData.id,
        across: that.data.bridgeData.across,
        len: that.data.bridgeData.len,
        name: that.data.bridgeData.name,
        totalBeton: that.data.bridgeData.totalBeton,
        totalCableBoom: that.data.bridgeData.totalCableBoom,
        totalRolledSteel: that.data.bridgeData.totalRolledSteel,
        totalStayCable: that.data.bridgeData.totalStayCable,
        totalSteelBar: that.data.bridgeData.totalSteelBar,
        totalSteelStrand: that.data.bridgeData.totalSteelStrand,
        spanExpression: that.data.bridgeData.spanExpression,
        width: that.data.bridgeData.width,
        organization: that.data.bridgeData.organization,
        structureTypeId: that.data.structureTypeId,
        structureTypeName: that.data.structureTypeName,
        structureTypeValue: that.data.structureTypeValue,
      },
      success: function(res) {

        wx.showToast({
          title: '提交成功！！！！',
          icon: 'success',
          duration: 1000,
        });
        setTimeout(function() {
          wx.switchTab({
            url: '../show',
            success: function(e) {
              var page = getCurrentPages().pop();
              if (page == undefined || page == null) return;
              page.onLoad();
            }
          })
        }, 500);
      }
    })
  },

  // picker发生改变 
  bindPickerChange(e) {
    this.setData({
      index: e.detail.value
    });
    var item = this.data.structureTypes[this.data.index];
    this.setData({
      structureTypeId: item.id,
      structureTypeName: item.name,
      structureTypeValue: item.code,
    });
  },

  // 监听是否输入长度和宽度 setData  input的值赋值给data
  inputBridgeData: function(e) {
    let dataKey = e.currentTarget.dataset.name;
    this.data.bridgeData[dataKey] = e.detail.value;
    if (this.data.bridgeData.len && this.data.bridgeData.across) {
      let len = this.data.bridgeData.len;
      let col = this.data.bridgeData.across;
      this.setData({
        average: len / col
      });
    }
  },
  // 表单验证规则设置
  initValidate() {

    // 验证字段的规则
    const rules = {
      //bridgeName: {
      //  required: true,
      //},
      len: {
        required: true,
        number: true,
      },
      across: {
        required: true,
        digits: true,
      },
      width: {
        required: true,
        number: true,
      },
      totalBeton: {
        required: true,
        number: true,
      },
      totalSteelStrand: {
        required: true,
        number: true,
      },
      totalSteelBar: {
        required: true,
        number: true,
      },
      totalRolledSteel: {
        required: true,
        number: true,
      },
      totalStayCable: {
        required: true,
        number: true,
      },
      totalCableBoom: {
        required: true,
        number: true,
      },
    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      len: {
        required: '请输入桥梁长度',
        number: '请输入正确的桥梁长度',
      },
      across: {
        required: '请输入跨数n',
        digits: '请输入正确的跨数n',
      },
      width: {
        required: '请输入桥梁宽度',
        number: '请输入正确的桥梁宽度',
      },
      totalBeton: {
        required: '请输入混凝土量',
        number: '请输入正确的混凝土数量',
      },
      totalSteelStrand: {
        required: '请输入钢绞线',
        number: '请输入正确的钢绞线量',
      },
      totalSteelBar: {
        required: '请输入普通钢筋量',
        number: '请输入正确的普通钢筋量',
      },
      totalRolledSteel: {
        required: '请输入钢材量',
        number: '请输入正确的钢材量',
      },
      totalStayCable: {
        required: '请输入斜拉索',
        number: '请输入正确的斜拉索量',
      },
      totalCableBoom: {
        required: '请输入主缆及吊杆',
        number: '请输入正确的主缆及吊杆量',
      }
    }

    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  // 弹出验证提示
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  bindCancel: function(e) {
    wx.navigateBack({});
  },
  // 使用navigateBack
  navigation: function(pageUrl, args) {
    var cps = getCurrentPages();
    var delta = 0;
    for (var i = cps.length - 1; i >= 0; i--) {
      if ("/" + cps[i].route == pageUrl) {
        if (delta == 0) {
          return;
        }

        wx.navigateBack({
          delta: delta
        });

        return;
      }

      delta++;
    }
    wx.navigateTo({
      url: pageUrl + args,
    })
  },

})